//
//  LoginViewController.m
//  budgetplan
//
//  Created by Barak on 10/27/12.
//  Copyright (c) 2012 Barak. All rights reserved.
//

#import "LoginViewController.h"
#import "PQHttpRequest.h"
#import "Account.h"
#import "AppDelegate.h"
#import "Card.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)login:(id)sender {

    _loading.hidden = NO;
    NSURL* loginUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@access/login", BASE_URL]];
    

    NSURLRequest *request = [NSURLRequest requestWithURL:loginUrl
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:30.0];
    
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];

}

// NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {
        NSString* username = self.usernameField.text;
        NSString* password = self.passwordField.text;
        
        NSLog(@"received authentication challenge");
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:username
                                                                    password:password
                                                                 persistence:NSURLCredentialPersistenceForSession];
        NSLog(@"credential created");
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        NSLog(@"responded to authentication challenge");
    }
    else {
        NSLog(@"previous authentication failure");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
}

// passed login
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    

    NSError* jsonError;
    
    id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&jsonError];
    
    NSString* token = [obj objectForKey:@"token"];
    ((AppDelegate*)[[UIApplication sharedApplication] delegate]).apiToken = token;

    [self retrieveAllDataForToken:token];
    
}


- (void) retrieveAllDataForToken:(NSString*)token {
    NSURL* accountsURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/operations/account/list", BASE_URL, token]];
    
    // get user accounts
    [PQHttpRequest getJSONFromURL:accountsURL response:^(id response, NSError *error) {
        NSLog(@"%@", response);
        
        // get first account id
        NSString* accountID = [[response objectForKey:@"data"] objectAtIndex:0];
      
        NSURL* accountURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/operations/account/%@", BASE_URL, token, accountID]];
        // get account data
        [PQHttpRequest getJSONFromURL:accountURL response:^(id accountResponse, NSError *error) {
            NSLog(@"%@", accountResponse);
            Account* account = [Account instanceFromDictionary:[accountResponse objectForKey:@"data"]];
            NSLog(@"IBAN %@", account.iban);
            
            // get holders (no real api)
            
            // get budget rules
            NSURL* budgetRulesUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@account_budget_rules.json?account_id=%@", OUR_SERVER_URL, account.accountId]];
            
            [PQHttpRequest getJSONFromURL:budgetRulesUrl response:^(id response, NSError *error) {
                NSMutableArray* budgetRules = [[NSMutableArray alloc] init];
                NSArray* rules = [response objectForKey:@"categories"];
                for (NSDictionary* ruleValues in rules) {
                    [budgetRules addObject:[BudgetRule instanceFromDictionary:ruleValues]];
                }
                
                [Account mainAccount].budgetRules = budgetRules;
                
                [self performSegueWithIdentifier:@"showMainController" sender:self];
                
                
            }];
            
            
           [self retrieveCards];
            
        }];
    }];
}


- (void) retrieveCards {
    
    NSString* token = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).apiToken;
    
    NSURL* cardListURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/operations/card/list", BASE_URL, token]];
    
    
    
    // get account data
    [PQHttpRequest getJSONFromURL:cardListURL response:^(id cardListResponse, NSError *error) {
        
        NSMutableArray* cards = [[NSMutableArray alloc] init];
        NSArray* cardIds = [cardListResponse objectForKey:@"data"];
        
        for (NSString* cardId in cardIds) {
            
            NSURL* getCardURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/operations/card/%@/status", BASE_URL, token, cardId]];
            
            [PQHttpRequest getJSONFromURL:getCardURL response:^(id cardResponse, NSError *error) {
                
                
                NSLog(@"ASDASD %@", cardResponse);
                [cards addObject:[Card instanceFromDictionary:[cardResponse objectForKey:@"data"]]];
                
                if (cards.count == cardIds.count){
                    [self setCardsToAccount:cards];
                }
            }];
        }
    }];
    
}

- (void) setCardsToAccount:(NSArray*)cards {
    NSArray* dummyHolderNames = @[@"Barak Edry", @"Rotem Bar", @"Ohad Asulin", @"Tal Aflalo"];
    NSArray* dummyColors = @[[UIColor colorWithRed:191.0f/255.0f green:130.0f/255.0f blue:2.0f/255.0f alpha:1],
                             [UIColor colorWithRed:160.0f/255 green:160.0f/255 blue:160.0f/255 alpha:1],
                             [UIColor colorWithRed:136.0f/255 green:169.0f/255 blue:159.0f/255 alpha:1],
                             [UIColor colorWithRed:0 green:100.0f/255 blue:235.0f/255 alpha:1]];
    
    for (int i=0; i < cards.count; i++) {
        Card* card= ((Card*)[cards objectAtIndex:i]);
        card.ownerName = [dummyHolderNames objectAtIndex:i];
        card.backgroundColor = [dummyColors objectAtIndex:i];
    }
    [Account mainAccount].cards = cards;
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

}



@end
